package com.whisperly.echotalk.account;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.whisperly.echotalk.bllmodel.CommonResponse;
import com.whisperly.echotalk.bllmodel.ResultBody;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.netWorkUtils.BlinkCallback;
import com.whisperly.echotalk.starryb.netWorkUtils.NetworkUtils;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.GlobalData;
import com.whisperly.echotalk.starryb.utils.MD5Utils;

import java.util.List;
import java.util.Locale;
import java.util.Objects;

public class AccountInfo extends AppCompatActivity {
    private UserWithChat user = new UserWithChat();
    private TextView user_name, user_email;
    private EditText user_relName, user_phone;
    private Button save_info;
    private String originalName, originalEmail, originalPhone, originalRelName;
    private Integer originalGender, genderId = null;
    private RadioGroup genderGroup;
    private View loadingView;

    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.account_info);
        loadingView = getLayoutInflater().inflate(R.layout.layout_loading, null);
        AppsManager.addActivity(this);

        user = GlobalData.getUser();

        user_name = findViewById(R.id.user_name);
        user_relName = findViewById(R.id.user_relName);
        user_email = findViewById(R.id.user_email);
        user_email.setEnabled(false);
        user_phone = findViewById(R.id.user_phone);
        save_info = findViewById(R.id.save_info);
        genderGroup = findViewById(R.id.gender);

        if (user.getObjectId() != null) {
            originalName = user.getName();
            originalRelName = user.getRelName();
            originalEmail = user.getEmail();
            originalPhone = user.getPhone();
            originalGender = user.getGender();

            user_name.setText(originalName);
            user_name.setEnabled(false);
            user_name.setBackgroundColor(Color.TRANSPARENT);
            user_relName.setText(originalRelName);
            user_email.setText(originalEmail);
            user_phone.setText(originalPhone);

            switch (originalGender) {
                case 0:
                    genderGroup.check(R.id.male);
                    genderId = 0;
                    break;
                case 1:
                    genderGroup.check(R.id.female);
                    genderId = 1;
                    break;
                case 2:
                    genderGroup.check(R.id.unknown);
                    genderId = 2;
                    break;
                default:
                    break;
            }
        }

        user_email.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (isValidEmail(user_email.getText().toString())) {
                    user_email.setError(getString(R.string.invalid_email_address));
                }
            }
        });

        genderGroup.setOnCheckedChangeListener((group, checkedId) -> {

            if (checkedId == R.id.male) {

                genderId = 0;
                System.out.println(genderId);
            } else if (checkedId == R.id.female) {

                genderId = 1;
                System.out.println(genderId);
            } else if (checkedId == R.id.unknown) {

                genderId = 2;
                System.out.println(genderId);
            }
        });
        save_info.setOnClickListener(v -> saveInfo());

    }

    private boolean isValidEmail(String email) {
        return !Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void saveInfo() {
        showLoading();
        new Handler(Looper.getMainLooper()).postDelayed(()->{
            if (genderId == null) {
                showModifyDialog1(getString(R.string.please_select_a_gender));
                hideLoading();
                return;
            }

            String relName = user_relName.getText().toString().trim();
            String phone = user_phone.getText().toString().trim();
            String email = user_email.getText().toString().trim();

            if ((email.equals(originalEmail) && phone.equals(originalPhone) && genderId.equals(originalGender))) {
                showModifyDialog1(getString(R.string.No_changes_were_made));
                hideLoading();
                return;
            }
            if (phone.isEmpty() || email.isEmpty() || relName.isEmpty()) {
                showModifyDialog1(getString(R.string.Please_dont_leave_it_blank));
                hideLoading();
                return;
            }
            if (phone.length() < 7) {
                showModifyDialog1(getString(R.string.The));
                user_phone.setError(getString(R.string.The));
                hideLoading();
                return;
            }
            if (phone.length() > 11) {
                showModifyDialog1(getString(R.string.The_number));
                user_phone.setError(getString(R.string.The_number));
                hideLoading();
                return;
            }
            if (isValidEmail(email)) {
                showModifyDialog1(getString(R.string.invalid_email_address));
                user_email.setError(getString(R.string.invalid_email_address));
                hideLoading();
                return;
            }


            UserWithChat userToUpdate = new UserWithChat(originalName, phone, email, genderId, relName);
            userToUpdate.setObjectId(GlobalData.getUser().getObjectId());
            NetworkUtils.update(userToUpdate, new BlinkCallback() {
                @Override
                public void onSuccess(ResultBody<?> response) {
                    if (response.getCode() == 200){
                        CommonResponse data = (CommonResponse)response.getData();
                        if (data.getSuccess()){
                            user.setPhone(phone);
                            user.setEmail(email);
                            user.setRelName(relName);
                            user.setGender(genderId);
                            showModifyDialog2(getString(R.string.Modification_successful), true);
                        }else {
                            if (data.getCode() == 1002){
                                showModifyDialog1(getString(R.string.The_phone));
                                user_phone.setError(getString(R.string.The_phone));
                                hideLoading();
                                return;
                            }

                            if (data.getCode() == 1003){
                                showModifyDialog1(getString(R.string.Failed_to_modify));
                                hideLoading();
                                return;
                            }

                            if (data.getCode() == 1004){
                                showModifyDialog1(getString(R.string.Failed_to_modify));
                                hideLoading();
                            }
                        }
                    }
                }

                @Override
                public void onFailure(Throwable throwable) {
                    showModifyDialog1(getString(R.string.Network_error));
                    hideLoading();
                }
            });
        },1000);
    }

    private void showModifyDialog2(String message, boolean flag) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.Prompt);
        builder.setMessage(message);
        builder.setPositiveButton(R.string.OK, (dialog, which) -> {
            if (flag) {
                Intent intent = new Intent(this, Account.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
//                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            }
            dialog.dismiss();
        }).setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void showModifyDialog1(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.Prompt);
        builder.setMessage(message);
        builder.setPositiveButton(R.string.OK, (dialog, which) -> {
            dialog.dismiss();
        }).setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void showLoading() {
        if (loadingView.getParent() == null) {
            ((ViewGroup) findViewById(android.R.id.content)).addView(loadingView);
            Log.d("LoginActivity", "Loading view added");
        }
    }

    private void hideLoading() {
        ((ViewGroup) findViewById(android.R.id.content)).removeView(loadingView);
    }
}
